<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>药品管理系统 - 库存管理</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
            background-color: #f5f7fa;
            color: #606266;
        }
        .app-container {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .logo-area {
            display: flex;
            align-items: center;
        }
        .logo {
            width: 50px;
            height: 50px;
            margin-right: 15px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            font-weight: bold;
        }
        .system-name {
            font-size: 22px;
            font-weight: bold;
        }
        .nav-menu {
            display: flex;
            background-color: #304156;
            padding: 0 20px;
        }
        .nav-item {
            padding: 15px 20px;
            color: #bfcbd9;
            cursor: pointer;
            transition: all 0.3s;
        }
        .nav-item:hover, .nav-item.active {
            color: #409EFF;
            background-color: #263445;
            border-bottom: 2px solid #409EFF;
        }
        .main-content {
            flex: 1;
            padding: 20px;
        }
        .card-container {
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        .search-bar {
            margin-bottom: 20px;
            padding: 20px;
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .pagination-container {
            margin-top: 20px;
            text-align: right;
        }
        .stats-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        .stat-card {
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
            text-align: center;
        }
        .stat-value {
            font-size: 24px;
            font-weight: bold;
            margin: 10px 0;
        }
        .stat-label {
            color: #909399;
            font-size: 14px;
        }
        .footer {
            text-align: center;
            padding: 15px 0;
            color: #909399;
            font-size: 14px;
            background-color: #f5f7fa;
            border-top: 1px solid #e6e6e6;
        }
        .warning-row {
            background-color: #fdf6ec !important;
        }
        .danger-row {
            background-color: #fef0f0 !important;
        }
        .normal-stock {
            color: #67C23A;
        }
        .warning-stock {
            color: #E6A23C;
        }
        .danger-stock {
            color: #F56C6C;
        }
        .batch-actions {
            margin-bottom: 15px;
        }
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        .filtered-count {
            margin-top: 10px;
            color: #909399;
            font-size: 14px;
        }
    </style>
</head>
<body>
<div id="app" class="app-container">
    <header class="header">
        <div class="logo-area">
            <div class="logo">药</div>
            <div class="system-name">药品管理系统</div>
        </div>
        <div>
            <el-dropdown @command="handleUserCommand">
                <span class="el-dropdown-link" style="color: white; cursor: pointer;">
                    {{ currentUser.username }} ({{ formatRole(currentUser.role) }})<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                    <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
    </header>

    <nav class="nav-menu">
        <div class="nav-item" @click="navigateTo('index.html')">首页</div>
        <div class="nav-item" @click="navigateTo('medicine.html')">药品管理</div>
        <div class="nav-item active">库存管理</div>
        <div class="nav-item" @click="navigateTo('sale.html')">销售管理</div>
        <div class="nav-item" @click="navigateTo('user.html')" v-if="currentUser.role === 'admin'">用户管理</div>
        <div class="nav-item" @click="navigateTo('log.html')" >操作日志</div>
    </nav>

    <main class="main-content">
        <h2 style="margin-bottom: 20px;">库存管理</h2>

        <div class="stats-container">
            <div class="stat-card">
                <div class="stat-label">库存药品总数</div>
                <div class="stat-value" style="color: #409EFF;">{{ inventoryStats.totalMedicines || 0 }}</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">库存预警数量</div>
                <div class="stat-value" style="color: #E6A23C;">{{ inventoryStats.lowStockCount || 0 }}</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">缺货药品数量</div>
                <div class="stat-value" style="color: #F56C6C;">{{ inventoryStats.outOfStockCount || 0 }}</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">库存总价值</div>
                <div class="stat-value" style="color: #67C23A;">¥{{ inventoryStats.totalValue || 0 }}</div>
            </div>
        </div>

        <div class="search-bar">
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="药品名称">
                    <el-input v-model="searchForm.medicineName" placeholder="请输入药品名称" clearable></el-input>
                </el-form-item>
                <el-form-item label="库存状态">
                    <el-select v-model="searchForm.stockStatus" placeholder="请选择库存状态" clearable>
                        <el-option label="正常" value="normal"></el-option>
                        <el-option label="预警" value="warning"></el-option>
                        <el-option label="缺货" value="danger"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="loadInventory">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                    <el-button type="success" @click="showThresholdDialog" v-if="currentUser.role === 'admin'">设置预警阈值</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="card-container">
            <div class="batch-actions" v-if="currentUser.role === 'admin' && selectedItems.length > 0">
                <el-button size="small" type="primary" @click="batchAdjustStock('in')">批量入库</el-button>
                <el-button size="small" type="warning" @click="batchAdjustStock('out')">批量出库</el-button>
                <span style="margin-left: 10px;">已选择 {{ selectedItems.length }} 项</span>
            </div>

            <div class="filtered-count" v-if="isFiltered">
                已筛选出 {{ filteredCount }} 条数据（共 {{ pagination.total }} 条）
                <el-button type="text" @click="resetSearch">清除筛选</el-button>
            </div>

            <el-table
                    :data="filteredInventoryList"
                    border
                    stripe
                    v-loading="loading"
                    @selection-change="handleSelectionChange"
                    :row-class-name="tableRowClassName">
                <el-table-column type="selection" width="55" v-if="currentUser.role === 'admin'"></el-table-column>
                <el-table-column prop="medicine.code" label="药品编码" width="120"></el-table-column>
                <el-table-column prop="medicine.name" label="药品名称" min-width="150"></el-table-column>
                <el-table-column prop="medicine.specification" label="规格" width="120"></el-table-column>
                <el-table-column prop="medicine.manufacturer" label="生产厂家" min-width="150"></el-table-column>
                <el-table-column prop="quantity" label="当前库存" width="100">
                    <template slot-scope="scope">
                        <span :class="getStockClass(scope.row)">
                            {{ scope.row.quantity }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="warningThreshold" label="最低库存" width="100"></el-table-column>
                <el-table-column label="库存状态" width="100">
                    <template slot-scope="scope">
                        <el-tag
                                size="small"
                                :type="getStockStatusType(scope.row)">
                            {{ getStockStatusText(scope.row) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" @click="handleAdjust(scope.row)">调整库存</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pagination.currentPage"
                        :page-sizes="[10, 20, 50, 100]"
                        :page-size="pagination.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pagination.total">
                </el-pagination>
            </div>
        </div>

        <!-- 调整库存对话框 -->
        <el-dialog
                :title="adjustDialogTitle"
                :visible.sync="adjustDialogVisible"
                width="500px"
                :close-on-click-modal="false">
            <el-form :model="adjustForm" :rules="adjustRules" ref="adjustForm" label-width="100px">
                <el-form-item label="药品名称">
                    <el-input v-model="adjustForm.medicineName" readonly></el-input>
                </el-form-item>
                <el-form-item label="当前库存">
                    <el-input v-model="adjustForm.currentStock" readonly></el-input>
                </el-form-item>
                <el-form-item label="最低库存" prop="warningThreshold">
                    <el-input-number
                            v-model="adjustForm.warningThreshold"
                            :min="0"
                            :max="10000"
                            style="width: 100%;"></el-input-number>
                </el-form-item>
                <el-form-item label="调整类型" prop="changeType">
                    <el-radio-group v-model="adjustForm.changeType">
                        <el-radio label="in">入库</el-radio>
                        <el-radio label="out">出库</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="调整数量" prop="quantity">
                    <el-input-number
                            v-model="adjustForm.quantity"
                            :min="1"
                            :max="adjustForm.changeType === 'out' ? adjustForm.currentStock : 10000"
                            style="width: 100%;"></el-input-number>
                </el-form-item>
                <el-form-item label="调整后库存">
                    <el-input :value="calculateNewStock()" readonly></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input
                            v-model="adjustForm.remark"
                            type="textarea"
                            :rows="3"
                            placeholder="请输入调整原因（可选）"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="adjustDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitAdjustForm">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 设置预警阈值对话框 -->
        <el-dialog
                title="设置库存预警阈值"
                :visible.sync="thresholdDialogVisible"
                width="400px">
            <el-form :model="thresholdForm" label-width="120px">
                <el-form-item label="全局预警阈值">
                    <el-input-number
                            v-model="thresholdForm.globalThreshold"
                            :min="1"
                            :max="1000"></el-input-number>
                </el-form-item>
                <el-form-item>
                    <el-alert
                            title="设置后，所有药品的最低库存将更新为此值"
                            type="info"
                            :closable="false">
                    </el-alert>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="thresholdDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateGlobalThreshold">确 定</el-button>
            </span>
        </el-dialog>
    </main>

    <footer class="footer">© 2023 药品管理系统 - 版权所有</footer>

    <!-- 全局加载层 -->
    <div class="loading-overlay" v-if="globalLoading">
        <el-button type="primary" :loading="true">加载中</el-button>
    </div>
</div>

<script>
    // 配置axios默认设置
    axios.defaults.baseURL = 'http://localhost:8080'; // 根据实际后端地址修改
    axios.defaults.withCredentials = true; // 允许携带cookie

    new Vue({
        el: '#app',
        data() {
            return {
                activeNav: 'inventory',
                currentUser: { id: null, username: '', role: '' },
                searchForm: {
                    medicineName: '',
                    stockStatus: ''
                },
                inventoryList: [], // 原始数据
                filteredInventoryList: [], // 筛选后的数据
                inventoryStats: {},
                loading: false,
                globalLoading: false,
                pagination: {
                    currentPage: 1,
                    pageSize: 10,
                    total: 0
                },
                selectedItems: [],
                adjustDialogVisible: false,
                adjustDialogTitle: '调整库存',
                adjustForm: {
                    id: '',
                    medicineName: '',
                    currentStock: 0,
                    warningThreshold: 0,
                    changeType: 'in',
                    quantity: 1,
                    remark: ''
                },
                adjustRules: {
                    warningThreshold: [
                        { required: true, message: '最低库存不能为空', trigger: 'blur' },
                        { type: 'number', min: 0, message: '最低库存不能小于0', trigger: 'blur' }
                    ],
                    changeType: [{ required: true, message: '请选择调整类型', trigger: 'change' }],
                    quantity: [{ required: true, message: '请输入调整数量', trigger: 'blur' }]
                },
                thresholdDialogVisible: false,
                thresholdForm: {
                    globalThreshold: 10
                }
            };
        },
        computed: {
            // 判断是否有筛选条件
            isFiltered() {
                return this.searchForm.medicineName || this.searchForm.stockStatus;
            },
            // 计算筛选后的数据条数
            filteredCount() {
                return this.filteredInventoryList.length;
            }
        },
        mounted() {
            this.loadCurrentUser();
            this.loadInventory();
        },
        methods: {
            loadCurrentUser() {
                this.globalLoading = true;
                axios.get('/pms/user/current').then(response => {
                    if (response.data.success) {
                        this.currentUser = response.data.data;
                        localStorage.setItem('currentUser', JSON.stringify(response.data.data));
                    } else {
                        this.$message.error(response.data.message);
                        window.location.href = 'login.html';
                    }
                    this.globalLoading = false;
                }).catch(error => {
                    console.error('获取用户信息失败:', error);
                    this.$message.error('获取用户信息失败');
                    this.globalLoading = false;
                    window.location.href = 'login.html';
                });
            },

            loadInventory() {
                this.loading = true;

                // 首先获取所有库存数据
                axios.get('/pms/inventory/list').then(response => {
                    if (response.data.success) {
                        // 假设返回的数据结构是数组
                        this.inventoryList = response.data.data.list || response.data.data;
                        this.pagination.total = this.inventoryList.length;

                        // 应用筛选条件
                        this.applyFilters();

                        // 计算统计数据
                        this.calculateStats();
                    } else {
                        this.$message.error(response.data.message);
                        if (response.data.message.includes("未登录")) {
                            window.location.href = 'login.html';
                        }
                    }
                    this.loading = false;
                }).catch(error => {
                    console.error('获取库存列表失败:', error);
                    this.$message.error('获取库存列表失败');
                    this.loading = false;
                    if (error.response && error.response.status === 401) {
                        window.location.href = 'login.html';
                    }
                });
            },

            // 应用筛选条件
            applyFilters() {
                let filteredData = [...this.inventoryList];

                // 按药品名称筛选
                if (this.searchForm.medicineName) {
                    const keyword = this.searchForm.medicineName.toLowerCase();
                    filteredData = filteredData.filter(item =>
                        item.medicine.name.toLowerCase().includes(keyword)
                    );
                }

                // 按库存状态筛选
                if (this.searchForm.stockStatus) {
                    filteredData = filteredData.filter(item => {
                        if (this.searchForm.stockStatus === 'normal') {
                            return item.quantity > item.warningThreshold;
                        } else if (this.searchForm.stockStatus === 'warning') {
                            return item.quantity > 0 && item.quantity <= item.warningThreshold;
                        } else if (this.searchForm.stockStatus === 'danger') {
                            return item.quantity === 0;
                        }
                        return true;
                    });
                }

                // 更新筛选后的数据和分页信息
                this.filteredInventoryList = filteredData;
                this.pagination.total = filteredData.length;
            },

            calculateStats() {
                // 计算统计数据（基于原始数据）
                this.inventoryStats = {
                    totalMedicines: this.inventoryList.length,
                    lowStockCount: this.inventoryList.filter(item =>
                        item.quantity > 0 && item.quantity <= item.warningThreshold).length,
                    outOfStockCount: this.inventoryList.filter(item =>
                        item.quantity === 0).length,
                    totalValue: this.inventoryList.reduce((sum, item) =>
                        sum + (item.quantity * (item.medicine.price || 0)), 0).toFixed(2)
                };
            },

            resetSearch() {
                this.searchForm = {
                    medicineName: '',
                    stockStatus: ''
                };
                // 重置筛选，显示所有数据
                this.filteredInventoryList = [...this.inventoryList];
                this.pagination.total = this.inventoryList.length;
            },

            handleSizeChange(size) {
                this.pagination.pageSize = size;
                // 这里可以根据需要实现服务端分页
                // 目前是前端分页，所以不需要重新加载数据
            },

            handleCurrentChange(page) {
                this.pagination.currentPage = page;
                // 这里可以根据需要实现服务端分页
                // 目前是前端分页，所以不需要重新加载数据
            },

            handleSelectionChange(selection) {
                this.selectedItems = selection;
            },

            tableRowClassName({row}) {
                if (row.quantity === 0) {
                    return 'danger-row';
                } else if (row.quantity <= row.warningThreshold) {
                    return 'warning-row';
                }
                return '';
            },

            getStockClass(row) {
                if (row.quantity === 0) {
                    return 'danger-stock';
                } else if (row.quantity <= row.warningThreshold) {
                    return 'warning-stock';
                }
                return 'normal-stock';
            },

            getStockStatusType(row) {
                if (row.quantity === 0) {
                    return 'danger';
                } else if (row.quantity <= row.warningThreshold) {
                    return 'warning';
                }
                return 'success';
            },

            getStockStatusText(row) {
                if (row.quantity === 0) {
                    return '缺货';
                } else if (row.quantity <= row.warningThreshold) {
                    return '预警';
                }
                return '正常';
            },

            handleAdjust(row) {
                this.adjustDialogTitle = `调整库存 - ${row.medicine.name}`;
                this.adjustForm = {
                    id: row.id,
                    medicineName: row.medicine.name,
                    currentStock: row.quantity,
                    warningThreshold: row.warningThreshold,
                    changeType: 'in',
                    quantity: 1,
                    remark: ''
                };
                this.adjustDialogVisible = true;

                if (this.$refs.adjustForm) {
                    this.$refs.adjustForm.clearValidate();
                }
            },

            calculateNewStock() {
                if (this.adjustForm.changeType === 'in') {
                    return this.adjustForm.currentStock + this.adjustForm.quantity;
                } else {
                    return this.adjustForm.currentStock - this.adjustForm.quantity;
                }
            },

            submitAdjustForm() {
                this.$refs.adjustForm.validate(valid => {
                    if (valid) {
                        // 构建更新数据
                        const updateData = {
                            id: this.adjustForm.id,
                            quantity: this.calculateNewStock(),
                            warningThreshold: this.adjustForm.warningThreshold
                        };

                        axios.put('/pms/inventory/update', updateData).then(response => {
                            if (response.data.success) {
                                this.$message.success(response.data.message);
                                this.adjustDialogVisible = false;
                                this.loadInventory(); // 重新加载数据
                            } else {
                                this.$message.error(response.data.message);
                                if (response.data.message.includes("权限不足")) {
                                    window.location.href = 'login.html';
                                }
                            }
                        }).catch(error => {
                            console.error('调整库存失败:', error);
                            this.$message.error('调整库存失败');
                            if (error.response && error.response.status === 403) {
                                this.$message.error('权限不足，无法执行此操作');
                            }
                        });
                    } else {
                        return false;
                    }
                });
            },

            batchAdjustStock(type) {
                if (this.selectedItems.length === 0) {
                    this.$message.warning('请选择要操作的药品');
                    return;
                }

                this.$prompt(`请输入${type === 'in' ? '入库' : '出库'}数量`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputPattern: /^[1-9]\d*$/,
                    inputErrorMessage: '请输入有效的数量'
                }).then(({ value }) => {
                    const quantity = parseInt(value);
                    const requests = this.selectedItems.map(item => {
                        const newQuantity = type === 'in' ?
                            item.quantity + quantity :
                            item.quantity - quantity;

                        if (newQuantity < 0) {
                            this.$message.error(`药品 ${item.medicine.name} 库存不足`);
                            return Promise.reject("库存不足");
                        }

                        return axios.put('/pms/inventory/update', {
                            id: item.id,
                            quantity: newQuantity,
                            warningThreshold: item.warningThreshold
                        });
                    });

                    Promise.all(requests).then(responses => {
                        const allSuccess = responses.every(response => response.data.success);
                        if (allSuccess) {
                            this.$message.success('批量调整成功');
                            this.loadInventory(); // 重新加载数据
                        } else {
                            this.$message.error('部分调整失败');
                        }
                    }).catch(error => {
                        console.error('批量调整失败:', error);
                        if (error !== "库存不足") {
                            this.$message.error('批量调整失败');
                        }
                    });
                }).catch(() => {});
            },

            showThresholdDialog() {
                this.thresholdForm.globalThreshold = 10;
                this.thresholdDialogVisible = true;
            },

            updateGlobalThreshold() {
                // 更新所有药品的最低库存阈值
                const requests = this.inventoryList.map(item => {
                    return axios.put('/pms/inventory/update', {
                        id: item.id,
                        warningThreshold: this.thresholdForm.globalThreshold,
                        quantity: item.quantity
                    });
                });

                Promise.all(requests).then(responses => {
                    const allSuccess = responses.every(response => response.data.success);
                    if (allSuccess) {
                        this.$message.success('全局阈值更新成功');
                        this.thresholdDialogVisible = false;
                        this.loadInventory(); // 重新加载数据
                    } else {
                        this.$message.error('部分阈值更新失败');
                        this.loadInventory(); // 即使部分失败也重新加载数据
                    }
                }).catch(error => {
                    console.error('更新全局阈值失败:', error);
                    this.$message.error('更新全局阈值失败');
                });
            },

            navigateTo(url) {
                window.location.href = url;
            },

            handleUserCommand(command) {
                if (command === 'profile') {
                    window.location.href = 'profile.html';
                } else if (command === 'logout') {
                    this.handleLogout();
                }
            },

            handleLogout() {
                axios.post('/pms/user/logout').then(response => {
                    if (response.data.success) {
                        this.$message.success(response.data.message);
                        localStorage.removeItem('currentUser');
                        window.location.href = 'login.html';
                    }
                }).catch(error => {
                    console.error('退出登录失败:', error);
                });
            },

            formatRole(role) {
                const roleMap = { 'admin': '管理员', 'sales': '销售员', 'inventory': '库存管理员' };
                return roleMap[role] || role;
            }
        }
    });
</script>
</body>
</html>